<template>
  <div>
    <tableComponents
      :isHaveExport="false"
      :isHaveAdd="false"
      :isShow="false"
      :isHavePagination="false"
    >
      <template v-slot:table>
        <el-row style="text-align: left; padding: 20px 0">
          <el-col :span="16">
            <el-button
              :loading="$store.state.isLoading"
              type="primary"
              @click="selProduct"
              >选择商品</el-button
            >
            <el-button :loading="$store.state.isLoading" @click="setHid">
              扫码入库
            </el-button>
            <el-button
              :loading="$store.state.isLoading"
              v-if="list.length > 0"
              @click="list = []"
            >
              全部清空
            </el-button>
            <el-button
              :loading="$store.state.isLoading"
              v-if="list.length > 0"
              @click="batchSet(0)"
            >
              批量设置数量
            </el-button>
            <el-button
              :loading="$store.state.isLoading"
              v-if="list.length > 0"
              @click="batchSet(1)"
            >
              批量设置进货价
            </el-button>
            <el-button
              :loading="$store.state.isLoading"
              v-if="list.length > 0"
              @click="batchSet(2)"
            >
              批量设置备注
            </el-button>
          </el-col>

          <el-col :span="8" style="text-align: right">
            <el-button
              :loading="$store.state.isLoading"
              type="primary"
              @click="toStockList"
            >
              进货明细
            </el-button>
            <el-button
              :loading="$store.state.isLoading"
              type="success"
              @click="saveStockAll"
            >
              入库
            </el-button>
          </el-col>
        </el-row>

        <el-table
          ref="multipleTable"
          :data="list"
          v-loading="loading"
          header-row-class-name="head_color"
          stripe
          tooltip-effect="dark"
          style="width: 99.9%"
          :summary-method="getSummaries"
          show-summary
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            align="center"
            width="50"
          ></el-table-column>
          <el-table-column
            type="index"
            align="center"
            width="50"
          ></el-table-column>
          <el-table-column label="商品名称" align="center" min-width="160">
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号/库存" align="center" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.hid || "----" }}
              <p>当前库存：{{ scope.row.all_stock || 0 }}</p>
              <div v-if="scope.row.label && scope.row.label.length > 0">
                <el-tag
                  v-for="(label, l) in scope.row.label"
                  style="margin-right: 5px; color: #ffffff; margin-left: 0"
                  size="mini"
                  :key="l"
                  effect="dark"
                >
                  {{ label }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品规格" align="center" min-width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.sku_ids == 0">无规格</span>
              <span v-else-if="scope.row.sku_id > 0">
                {{ scope.row.sku_cn || "----" }}
              </span>
              <el-link
                type="primary"
                @click="selectSkuItem(scope.row, scope.$index)"
                v-else
              >
                选择规格
              </el-link>
              <!-- <el-link
                type="primary"
                @click="selectSkuItem(scope.row, scope.$index)"
                v-if="scope.row.sku_id > 0 && scope.row.sku_ids > 0"
                style="margin-left: 5px"
              >
                修改
              </el-link> -->
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            align="center"
            min-width="120"
            prop="stock"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="进货价" align="center" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="总金额"
            align="center"
            min-width="120"
            prop="price_all"
          >
            <template slot-scope="scope">
              {{ (scope.row.stock * scope.row.price) | keepTwoNum }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                @click="delShopsItem(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </tableComponents>

    <el-drawer
      :visible.sync="show_pro"
      direction="rtl"
      :modal="true"
      size="65%"
      class="user_edit_drawer"
    >
      <productLists
        v-if="show_pro"
        @sendItem="sendItem"
        @close="show_pro = false"
      />
    </el-drawer>

    <el-drawer
      :visible.sync="show_sku"
      direction="rtl"
      :modal="true"
      size="40%"
      class="user_edit_drawer"
    >
      <div
        style="
          padding: 0px 20px 20px;
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          font-size: 16px;
        "
        class="tl"
      >
        <div class="fx" style="margin: 10px 0 40px; font-size: 20px">
          {{ editInfo.title }}
        </div>
        <div v-for="(item, i) in editInfo.attr" :key="i">
          <p>{{ item.title }}</p>
          <div style="margin: 10px 0 20px">
            <el-tag
              v-for="(sku, s) in item.info"
              :key="s"
              :type="sku.sku_title"
              :effect="skuForm[sku.parent_id] == sku.sku_id ? 'dark' : 'plain'"
              style="margin-right: 20px; margin-left: 0; font-size: 15px"
              @click="selSku(item, sku)"
            >
              {{ sku.sku_title }}
            </el-tag>
          </div>
        </div>
        <div class="fx" style="margin: 50px 0 0; font-size: 17px">
          已选规格：{{ skuTitle || "---" }}
        </div>
        <div class="tc" style="margin-top: 100px">
          <el-button
            type="primary"
            :loading="$store.state.isLoading"
            @click="saveSku()"
          >
            确定
          </el-button>
        </div>
      </div>
    </el-drawer>

    <el-dialog
      :close-on-click-modal="false"
      title="批量设置"
      :modal-append-to-body="false"
      :visible.sync="show_edit"
      class="tl size_13"
      width="700px"
    >
      <el-form label-width="140px">
        <el-form-item label="入库数量" v-if="edit_index == 0">
          <el-col :span="20">
            <el-input v-model="stock" size="small"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="进货价" v-if="edit_index == 1">
          <el-col :span="20">
            <el-input v-model="price" size="small"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" v-if="edit_index == 2">
          <el-col :span="20">
            <el-input v-model="remark" size="small"></el-input>
          </el-col>
        </el-form-item>
        <div class="tc">
          <el-button
            :loading="$store.state.isLoading"
            size="small"
            @click="batchGet"
          >
            确定
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="扫码入库"
      :modal-append-to-body="false"
      :visible.sync="show_hid"
      class="tl size_13"
      width="700px"
    >
      <el-form label-width="140px">
        <el-form-item label="商品编号">
          <el-col :span="20">
            <el-input v-model="hid" size="small"></el-input>
          </el-col>
        </el-form-item>
        <div class="tc">
          <el-button
            :loading="$store.state.isLoading"
            size="small"
            @click="getHid"
          >
            确定
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import productLists from "@/components/shop/stock/product_lists.vue";
export default {
  data() {
    return {
      loading: false,
      list: [],
      show_pro: false,
      show_sku: false,
      show_edit: false,
      edit_index: -1,
      editInfo: {},
      skuForm: {},
      multipleSelection: [],
      stock: "",
      price: "",
      remark: "",
      hid: "",
      show_hid: false,
    };
  },
  components: {
    productLists,
  },
  computed: {
    nowSku() {
      let arr = this.editInfo.sku_json || [];
      let nowselIndex = -1;
      arr.forEach((item, i) => {
        let skuObj = item.sku_obj;
        var flag = true;
        for (let key in skuObj) {
          if (skuObj[key] != this.skuForm[key]) {
            flag = false;
          }
        }
        if (flag) {
          nowselIndex = i;
        }
      });
      return arr[nowselIndex] || {};
    },
    skuTitle() {
      var str = "";
      if (this.nowSku && this.nowSku.id) {
        for (let i in this.nowSku) {
          if (!isNaN(i)) {
            str += this.nowSku[i] + ";";
          }
        }
        if (str) {
          str = str.substr(0, str.length - 1);
        }
      }
      return str;
    },
  },
  created() {
    if (this.$route.query.pid) {
      this.getDataByPid();
    }
  },
  methods: {
    getDataByPid() {
      var params = {};
      params.id = this.$route.query.pid;
      this.$api.getShops.selectShopsItem(params).then((res) => {
        if (res.data.code == 200) {
          var item = res.data.result;
          if (item.attr) {
            item.attr = JSON.parse(item.attr) || [];
          } else {
            item.attr = [];
          }
          this.sendItem(item);
        }
      });
    },
    //加入列表
    getHid() {
      var params = {};
      params.hid = this.hid;
      this.$api.getShops.product_stock_findhid(params).then((res) => {
        if (res.data.status == 1 && res.data.code == 200) {
          let index = this.list.findIndex(
            (item) =>
              item.hid == res.data.result.hid && item.pid == res.data.result.pid
          );
          if (index > -1) {
            this.list[index].stock = this.list[index].stock + 1;
          } else {
            var obj = {};
            obj.pid = res.data.result.pid;
            obj.title = res.data.result.product.title;
            obj.sku_ids = res.data.result.product.sku_id || 0;
            obj.sku_id = res.data.result.id;
            obj.sku_iden = res.data.result.iden;
            obj.hid = res.data.result.hid;
            obj.price = this.$fnc.toFixedZ(res.data.result.cost_price);
            obj.all_stock = res.data.result.stock;
            obj.sku_cn = res.data.result.sku_cn;
            obj.stock = 1;
            obj.remark = "";
            obj.sku_json = res.data.result.sku_json || [];
            obj.attr = res.data.result.attr || [];
            this.list.push(obj);
          }
          this.$message.success("添加成功");
        } else {
          this.$fnc.alertError(res.data.code_desc, res.data.result);
        }
      });
    },
    //扫码入库
    setHid() {
      this.hid = "";
      this.show_hid = true;
    },
    //进货明细
    toStockList() {
      this.$router.push({
        path: "/index/shop/product_stock?types=1&is_extract=0",
      });
    },
    //入库
    saveStockAll() {
      if (this.list.length == 0) {
        this.$message.error("请选择入库商品");
        return;
      }

      let dataList = [];
      for (let i in this.list) {
        if (this.list[i].sku_ids > 0 && this.list[i].sku_id == 0) {
          this.$fnc.alertError(
            "未选择商品规格",
            `序号：${Number(i) + 1}；商品名称：${this.list[i].title}`
          );
          return;
        } else if (this.list[i].stock == 0 || this.list[i].stock == "") {
          this.$fnc.alertError(
            "未填写入库数量",
            `序号：${Number(i) + 1}；商品名称：${this.list[i].title}`
          );
          return;
        }
        dataList.push({
          pid: this.list[i].pid,
          sku_id: this.list[i].sku_id,
          price: this.list[i].price,
          stock: this.list[i].stock,
          remark: this.list[i].remark,
          sku_iden: this.list[i].sku_iden,
          sku_cn: this.list[i].sku_cn,
        });
      }
      var params = {};
      params.stocks = JSON.stringify(dataList);
      this.$api.getShops.product_stock_batch_save(params).then((res) => {
        if (res.data.status == 1 && res.data.code == 200) {
          this.$fnc.alertSuccess({ text: "入库成功" });
          this.list = [];
        } else {
          this.$fnc.alertError(res.data.code_desc, res.data.result);
        }
      });
    },
    //批量设置
    batchGet() {
      let key = "";
      if (this.edit_index == 0) {
        key = "stock";
      } else if (this.edit_index == 1) {
        key = "price";
      } else if (this.edit_index == 2) {
        key = "remark";
      }

      for (let i in this.multipleSelection) {
        if (this.edit_index == 0) {
          this.multipleSelection[i][key] = this.stock || "";
        } else if (this.edit_index == 1) {
          this.multipleSelection[i][key] = this.price || "";
        } else if (this.edit_index == 2) {
          this.multipleSelection[i][key] = this.remark || "";
        }
      }
      this.edit_index = -1;
      this.show_edit = false;
    },
    //批量设置数量
    batchSet(int) {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择商品");
        return;
      }
      this.stock = "";
      this.price = "";
      this.remark = "";
      this.edit_index = int;
      this.show_edit = true;
    },
    //确认规格
    saveSku() {
      var flag = true;
      for (let key in this.skuForm) {
        if (!this.skuForm[key]) {
          flag = false;
          break;
        }
      }
      if (flag) {
        this.list[this.editInfo.index].sku_id = this.nowSku.id;
        this.list[this.editInfo.index].sku_cn = this.skuTitle;
        this.list[this.editInfo.index].sku_iden = this.nowSku.iden;
        this.list[this.editInfo.index].hid = this.nowSku.hid;
        this.list[this.editInfo.index].price = this.$fnc.toFixedZ(
          this.nowSku.cost_price
        );
        this.list[this.editInfo.index].all_stock = this.nowSku.stock;
        this.show_sku = false;
      } else {
        this.$fnc.alertError("请选择商品规格");
      }
    },
    //选择规格
    selSku(item, sku) {
      if (item.info && item.info[0] && item.info[0].parent_id) {
        this.$set(this.skuForm, sku.parent_id, sku.sku_id);
      }
    },
    //选择规格
    selectSkuItem(item, index) {
      this.skuForm = {};
      this.editInfo = JSON.parse(JSON.stringify(item));
      this.editInfo.index = index;
      let skuJson = this.editInfo.sku_json;
      skuJson.forEach((item, i) => {
        var sku_arr = item.iden.split("@");
        var sku_obj = {};
        sku_arr.forEach((sku, s) => {
          var sku_item = sku.split(":");
          sku_obj[sku_item[0]] = sku_item[1];
        });
        item.sku_obj = sku_obj;
      });
      this.editInfo.sku_json = skuJson;
      this.show_sku = true;
    },
    //删除商品
    delShopsItem(index) {
      this.list.splice(index, 1);
    },
    //添加商品
    sendItem(item) {
      let arr = [];
      let obj = {};
      obj.pid = item.id;
      obj.title = item.title;
      obj.sku_ids = item.sku_id;
      obj.sku_json = item.sku_json || [];
      obj.attr = item.attr || [];
      obj.label = item.label || [];

      for (let i in item.sku_json) {
        obj.sku_id = item.sku_json[i].id || 0;
        obj.sku_iden = item.sku_json[i].iden || "";
        obj.hid = item.sku_json[i].hid || "";
        obj.price = this.$fnc.toFixedZ(item.sku_json[i].cost_price || 0);
        obj.all_stock = item.sku_json[i].stock || 0;
        let str = "";
        for (let s in item.sku_json[i]) {
          if (!isNaN(s)) {
            str += item.sku_json[i][s] + ";";
          }
        }
        if (str) {
          str = str.substr(0, str.length - 1);
        }
        obj.sku_cn = str;
        obj.stock = 1;
        obj.remark = "";
        arr.push(JSON.parse(JSON.stringify(obj)));
      }
      this.list = this.list.concat(arr);
    },
    //选择商品
    selProduct() {
      this.show_pro = true;
    },
    //表格统计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          !values.every((value) => isNaN(value)) &&
          column.property != "price_all"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else if (column.property == "price_all") {
          const price_alls = data.map((item) => [
            Number(item.price),
            Number(item.stock),
          ]);
          sums[index] = price_alls.reduce((prev, curr) => {
            const value = Number(Number(curr[0]) * Number(curr[1]));
            if (!isNaN(value)) {
              return prev + value;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style>
</style>